<?php

use Biz\model\package\PackageOrderLog;
use Doraemon\tools\Log;
use Hhz\AdministrativeRegion\Region;

class OrderAddressAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_REGISTER;

    const CHECK_SAFECODE = true;

    public function main()
    {
        $uid = $this->uid;
        $consigneeName = $this->getRequest()->getPost('accept_name');
        $consigneePhone = $this->getRequest()->getPost('mobile');
        $province = $this->getRequest()->getPost('province');
        $city = $this->getRequest()->getPost('city');
        $infoAddress = $this->getRequest()->getPost('info_address');
        $consigneeDetailInfo = $this->getRequest()->getPost('address');
        $addressId = $this->getRequest()->getPost('address_id');
        $areaCode = $this->getRequest()->getPost('area_code');
        $orderNo = $this->getRequest()->getPost('order_no');
        $area = $areaCode;
        if (!empty($areaCode)) {
            $province = substr($areaCode, 0, 2) . '0000';
            $city = Region::getCityCode($areaCode);
        }

        $appType = $this->appType;
        Log::info('package-order-log', [$uid, $areaCode, $consigneeName, $consigneePhone, $province, $city, $area, $infoAddress, $consigneeDetailInfo, $addressId]);
        if (empty($consigneeName) || empty($consigneePhone) || empty($province) || empty($city) || empty($area) || empty($infoAddress) || empty($consigneeDetailInfo)) {
            Log::info('point-order-log', [$uid, '地址异常']);
            throw new \Exception('地址异常', self::CODE_ERROR_VIEW_TOSTA);
        }

        $rawData = compact('addressId', 'consigneeName', 'consigneePhone', 'province', 'city',
            'area', 'infoAddress', 'consigneeDetailInfo', 'uid', 'appType', 'orderNo');


        try {
            $res = \Biz\service\package\PackageOrder::updateOrderAddress($rawData);
        } catch (Exception $e) {
            $data = array_merge($rawData, ['errorCode' => $e->getCode(), 'errorLine' => $e->getLine(), 'errorMsg' => $e->getMessage()]);
            $log = [
                'log_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
                'log_type' => PackageOrderLog::LOG_TYPE_5,
                'log' => '订单修改失败',
                'order_no' => $orderNo,
            ];
            PackageOrderLog::add($log);
            Log::info('订单创建失败', $data);
            throw new \Exception($e->getMessage(), self::CODE_ERROR_VIEW_TOSTA);
        }
        $result = ['order_no' => $orderNo];
        $this->setSuccess($result, self::API_CODE_SUCCES);
    }
}